package vikaa.ui;

import java.util.ArrayList;

import vikaa.adapter.ContactFriendListAdapter;
import vikaa.bean.WeiboFriend;
import vikaa.timelinepackage.Timeline;
import vikaa.tools.DialogService;
import vikaa.wowo.R;
import vikaa.wowo.cache.InvitorSqlStoragePrivate;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

public class ContactFriendChoose extends Activity implements OnItemClickListener{
	private LinearLayout backBtn;
	private EditText searchEdt;
	private ListView wb_fd_listview;
	private ContactFriendListAdapter mAdapter;
	private ArrayList<WeiboFriend> wbfList = new ArrayList<WeiboFriend>() ;
	public ArrayList<WeiboFriend> mList = new ArrayList<WeiboFriend>();
	public static boolean callflag = false;
	public static boolean inviteflag = false;
	private InputMethodManager imm;
	private ImageView submitBtn;
	private LinearLayout header;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wowo_contact_choose);
		header = (LinearLayout)findViewById(R.id.header);
		initview();
		initdata();
	}

	public void initview(){
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		wb_fd_listview = (ListView) findViewById(R.id.wowolist);
		wb_fd_listview.setOnItemClickListener(this);
		mAdapter = new ContactFriendListAdapter(ContactFriendChoose.this, mList, wb_fd_listview);
		wb_fd_listview.setAdapter(mAdapter);
		//DialogService.showProgressDialog(ContactFriendChoose.this, getString(R.string.get_friend));
		searchEdt = (EditText)findViewById(R.id.searchEdt);
        searchEdt.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(keyCode == 66 && event.getAction() == KeyEvent.ACTION_DOWN){
					DialogService.hideSoftKeypad(ContactFriendChoose.this);
					//DialogService.showProgressDialog(ContactFriendChoose.this, getString(R.string.get_friend));
					new SearchFriendThread(searchEdt.getText().toString()).start();
				}
				return false;
			}
		});
        searchEdt.addTextChangedListener(new TextWatcher() {
       	 private CharSequence temp;
            private int editStart ;
            private int editEnd ;
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				temp = s;
			}
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			public void afterTextChanged(Editable s) {
				if(temp.length() ==0){
					editStart = searchEdt.getSelectionStart();
		            editEnd = searchEdt.getSelectionEnd();
		            if(temp.length() == 0){
		            	mList.clear();
						mAdapter.notifyDataSetChanged();
						initdata();
		            }
				}
			}
		});
        if(callflag || inviteflag){
        	submitBtn = (ImageView)findViewById(R.id.submitBtn);
        	submitBtn.setVisibility(View.VISIBLE);
        	submitBtn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					//imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
					wbfList.clear();
					wbfList = InvitorSqlStoragePrivate.getChoosedinSql(getApplicationContext());
					switch(wbfList.size()){
					case 0:
						new AlertDialog.Builder(ContactFriendChoose.this).setTitle("提示").setMessage("请选择好友进行召唤")
						.setPositiveButton("返回", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
							}
						}).show();
						break;
						default:
							if(inviteflag){
								WowoCreate4.inviteflag = true;
								Intent i = new Intent(ContactFriendChoose.this,WowoCreate4.class);
								i.putExtra("name", Timeline.space_name);
								i.putExtra("state", Timeline.state);
								startActivity(i);
							}
							break;
					}
				}
			});
        }else{
        	submitBtn = (ImageView)findViewById(R.id.submitBtn);
        	submitBtn.setVisibility(View.INVISIBLE);
        }
	}
	public void initdata(){
	    if ((wbfList=InvitorSqlStoragePrivate.getContactfdFromSql(getApplicationContext())).size()>0){ 
			Message msg = mhandler.obtainMessage(1);
			msg.obj = wbfList;
			msg.sendToTarget();
	    }
	    else
	    	new GetFriendThread().start();
	}
	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what){
			case 1:
				header.setVisibility(View.GONE);
				//DialogService.closeProgressDialog();
				if(msg.obj != null){
					ArrayList<WeiboFriend> strings = (ArrayList<WeiboFriend>) msg.obj;
					if(!strings.isEmpty()){
						mList.addAll(strings);
						mAdapter.notifyDataSetChanged();
					}
				}
				break;
			case 2:
				header.setVisibility(View.GONE);
				//DialogService.closeProgressDialog();
				if(msg.obj != null){
					ArrayList<WeiboFriend> strings = (ArrayList<WeiboFriend>) msg.obj;
					if(!strings.isEmpty()){
						mList.clear();
						mList.addAll(strings);
						mAdapter.notifyDataSetChanged();
					}
				}
				break;
			}
		}
	};
	public void getContact(){
		Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);     
		while(cursor.moveToNext()){
			WeiboFriend wf = new WeiboFriend();
			String phoneName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 
			 int phoneCount = cursor
                     .getInt(cursor
                             .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
			if (phoneCount > 0){
			/*Cursor phonecur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
					ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
			while(phonecur.moveToNext()){
				String phoneNum = phonecur.getString(phonecur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				Log.i("af", phoneNum);
				if(StringUtils.isMobileNO(phoneNum)){
					wf.setId(phoneNum);
					wf.setName(phoneName);
					wf.setPhone(phoneNum);
					wf.setSelected(false);
					wbfList.add(wf);
				}
			}
			phonecur.close();*/
			  Cursor phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
	                  ContactsContract.CommonDataKinds.Phone.CONTACT_ID
	                          + "=" + contactId, null, null);
	          if(phoneCursor.moveToFirst())  {
	              do  {
	                  //遍历所有的联系人下面所有的电话号码
	                  String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
	                  if(phoneNumber.length() > 10){
	                	  wf.setId(phoneNumber);
						  wf.setName(phoneName);
						  wf.setPhone(phoneNumber);
						  wf.setSelected(false);
						  wbfList.add(wf);
	                  }
	              }while(phoneCursor.moveToNext());
	          }
	          phoneCursor.close();
			}
		}
		cursor.close();
	}

	class GetFriendThread extends Thread{
		private boolean isrun = true;
		@Override
		public void run() {
			while(isrun){
				try{
					isrun = false;
					getContact();
					if(wbfList.size()>0)InvitorSqlStoragePrivate.SaveContactfdInSql(wbfList,getApplicationContext());
					Message msg = mhandler.obtainMessage(1);
					msg.obj = InvitorSqlStoragePrivate.getContactfdFromSql(getApplicationContext());
					msg.sendToTarget();
				}catch(Exception e){
					isrun = false;
					e.printStackTrace();
				}
			}
		}
	}
	class SearchFriendThread extends Thread{
		private boolean isrun = true;
		private String value;
		public SearchFriendThread(String value) {
			super();
			this.value = value;
		}
		@Override
		public void run() {
			while(isrun){
				isrun = false;
				try{
					wbfList.clear();
					for(int i=0;i<mList.size();i++){
						if(mList.get(i).getName().indexOf(value) != -1 || mList.get(i).getPhone().indexOf(value) != -1){
							WeiboFriend wf = new WeiboFriend();
							wf.setId(mList.get(i).getId());
							wf.setName(mList.get(i).getName());
							wf.setPhone(mList.get(i).getPhone());
							wf.setSelected(false);
							wbfList.add(wf);
						}
					}
					Message msg = mhandler.obtainMessage(2);
					msg.obj = wbfList;
					msg.sendToTarget();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
		WeiboFriend wf = new WeiboFriend();
    	String id = mList.get(position).getId();
    	String name = mList.get(position).getName();
        wf.setId(id);
        wf.setName(name);
        wf.setPhone(mList.get(position).getPhone());
        InvitorSqlStoragePrivate.updateContactfdSql(id, !(mList.get(position).isSelected()),getApplicationContext());
        if(!(mList.get(position).isSelected()) == true){
        	InvitorSqlStoragePrivate.saveChoosedinSql(wf, getApplicationContext());
        }else{
        	InvitorSqlStoragePrivate.delectChoosedinSql(wf,getApplicationContext());
        }
        mAdapter.changeState(position,view);
	}
}
